{{Extend "db/index"}}
{{Block "title"}}{{if eq (Form "operation") "modifyTable"}}{{"修改表"|T}}: {{Stored.table}}{{else}}{{"创建表"|T}}{{end}} - {{Super}}{{/Block}}
{{Block "breadcrumb"}}
{{Super}}
<li><a href="{{dbMgrURL "listTable" Stored.dbName}}" data-pjax="#pcont" data-keepjs="true">{{Stored.dbName}}</a></li>
<li class="active">{{if eq (Form "operation") "modifyTable"}}{{"修改表"|T}}: {{Stored.table}}{{else}}{{"创建表"|T}}{{end}}</li>
{{/Block}}
{{Block "main"}}
<style>
    .table > tbody > tr > td.actions{line-height:2.1em;padding:0;text-align:center}
</style>
<div class="row">
    <div class="col-md-12">
        {{Include "db/mysql/results"}}
        <div class="block-flat">
          <div class="header">							
            <h3>
                {{if eq (Form "operation") "modifyTable"}}{{"修改表"|T}}: {{Stored.table}}{{else}}{{"创建表"|T}}{{end}}
            </h3>
          </div>
          <div class="content">
              <form class="form-horizontal group-border-dashed" method="POST" action="">
              <div class="form-group">
                <label class="col-sm-2 control-label">{{"表名"|T}}</label>
                <div class="col-sm-9">
                    <input type="text" name="name" class="form-control" required="required" value="{{Form "name"}}">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">{{"引擎"|T}}</label>
                <div class="col-sm-9">
                    <select name="engine" class="form-control" id="engine">
                        {{if Stored.engines}}
                        {{$engine := Form "engine"}}
                        {{range $k,$v := Stored.engines}}
                        <option value="{{$v.Engine.String}}"{{if eq $v.Engine.String $engine}} selected="selected"{{end}}>{{$v.Engine.String}}</option>
                        {{end}}
                        {{end}}
                    </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">{{"字符集"|T}}</label>
                <div class="col-sm-9">
                    {{$collation := Form "collation"}}
                    <select name="collation" class="form-control" id="collation" rel="{{if $collation}}{{$collation}}{{else}}utf8_general_ci{{end}}">
                        <option value="" readonly="readonly">loading...</option>
                    </select>
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">{{"自增起始值"|T}}</label>
                <div class="col-sm-9">
                    <input type="number" name="ai_start_val" class="form-control" value="{{Form "ai_start_val"}}">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">{{"注释"|T}}</label>
                <div class="col-sm-9">
                    <input type="text" name="comment" class="form-control" value="{{Form "comment"}}">
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-1 control-label"></label>
                <div class="col-sm-10">
                <div class="table-responsive">
				<table class="table no-border hover blue">
					<thead class="no-border">
						<tr>
							<th style="width: 150px"><strong>{{"字段名"|T}}</strong></th>
                            <th><strong>{{"类型"|T}}</strong></th>
                            <th style="width: 70px"><strong>{{"长度"|T}}</strong></th>
                            <th><strong>{{"选项"|T}}</strong></th>
                            <th><strong>{{"NULL"|T}}</strong></th>
                            <th><input type="radio" name="auto_increment" value=""><strong>{{"自增"|T}}</strong></th>
                            <th style="width: 180px"><strong>{{"默认值"|T}}</strong></th>
                            <th><strong>{{"注释"|T}}</strong></th>
                            <th style="width: 70px"><a href="javascript:;" onclick="addRow()" class="label label-success" title="{{"下一行插入"|T}}"><i class="fa fa-plus"></i></a></th>
						</tr>
					</thead>
					<tbody class="no-border-x" id="tbody-content">
                        {{range $index, $field := Stored.postFields}}
                        <tr>
							<td>
                                <input type="text" name="fields[{{$index}}][field]" value="{{$field.Field}}" class="form-control">
                                <input type="hidden" name="fields[{{$index}}][orig]" value="{{$field.Field}}">
                            </td>
                            <td><select name="fields[{{$index}}][type]" class="form-control" onchange="onselectType(this)">
                                {{range $k, $group := Stored.typeGroups}}
                                <optgroup label="{{$group.Label}}" data-type="{{$group.Type}}">
                                    {{range $k, $t := $group.Types}}
                                    <option value="{{$t.Name}}"{{if eq $field.Type $t.Name}} selected="selected"{{end}}>{{$t.Name}}</option>
                                    {{end}}
                                </optgroup>
                                {{end}}
                                {{if Stored.foreignKeys}}
                                <optgroup label="{{"外键"|T}}" data-type="ForeignKey">
                                    {{range $k, $v := Stored.foreignKeys}}
                                    <option value="{{$k}}"{{if eq $field.Type $k}} selected="selected"{{end}}>{{$v}}</option>
                                    {{end}}
                                </optgroup>
                                {{end}}
                            </select></td>
							<td><input type="text" name="fields[{{$index}}][length]" value="{{$field.Length}}" class="form-control"></td>
                            <td><select name="fields[{{$index}}][collation]" class="form-control select-collation"{{if and $field.Type (isString $field.Type)}}{{else}} style="display:none"{{end}} rel="{{$field.Collation}}">
                                <option value="" readonly="readonly">loading...</option>
                            </select>
                                <select name="fields[{{$index}}][unsigned]" class="form-control"{{if or (not $field.Type) (isNumeric $field.Type)}}{{else}} style="display:none"{{end}}>
                                    <option value=""></option>
                                    {{range $k,$v:=Stored.unsignedTags}}
                                    <option value="{{$v}}"{{if eq $field.Unsigned $v}} selected="selected"{{end}}>{{$v}}</option>
                                    {{end}}
                                </select>
                                <select name="fields[{{$index}}][on_update]" class="form-control"{{if or (eq $field.Type "timestamp") (eq $field.Type "datetime")}}{{else}} style="display:none"{{end}}>
                                    <option value="">(ON UPDATE)</option>
                                    <option value="CURRENT_TIMESTAMP"{{if eq $field.On_update "CURRENT_TIMESTAMP"}} selected="selected"{{end}}>CURRENT_TIMESTAMP</option>
                                </select>
                                <select name="fields[{{$index}}][on_delete]" class="form-control" style="display:none">
                                    <option value="">(ON DELETE)</option>
                                    {{range $k,$v:=Stored.onActions}}
                                    <option value="{{$v}}"{{if eq $field.On_delete $v}} selected="selected"{{end}}>{{$v}}</option>
                                    {{end}}
                                </select>
                            </td>
                            <td><label class="x-block"><input type="checkbox" name="fields[{{$index}}][null]" value="1"{{if $field.Null}} checked="checked"{{end}}></label></td>
                            <td><label class="x-block"><input type="radio" name="auto_increment" value="{{$index}}"{{if $field.AutoIncrement.Valid}} checked="checked"{{end}}></label></td>
                            <td>
                                <div class="input-group">
                                    <label class="input-group-addon">
                                        <input type="checkbox" name="fields[{{$index}}][has_default]" value="1"{{if $field.Default.Valid}} checked="checked"{{end}}>
                                    </label>
                                    <input type="text" name="fields[{{$index}}][default]" value="{{$field.Default.String}}" class="form-control" onkeyup="$(this).trigger('change')" onchange="$(this).prev('label').children('input').prop('checked',true)">
                                </div>
                            </td>
                            <td><input type="text" name="fields[{{$index}}][comment]" value="{{$field.Comment}}" class="form-control"></td>
                            <td class="actions">
                                <a href="javascript:;" onclick="addRow(this)" class="label label-success" title="{{"下一行插入"|T}}"><i class="fa fa-plus"></i></a>
                                <a href="javascript:;" onclick="moveUpRow(this)" class="label label-primary" title="{{"上移"|T}}"><i class="fa fa-arrow-up"></i></a>
                                <a href="javascript:;" onclick="delRow(this)" class="label label-danger" title="{{"移除"|T}}"><i class="fa fa-times"></i></a>
                                <a href="javascript:;" onclick="moveDownRow(this)" class="label label-primary" title="{{"下移"|T}}"><i class="fa fa-arrow-down"></i></a>
                            </td>
						</tr>
                        {{end}}
					</tbody>
				</table>
			    </div>

{{if Stored.supportPartitioning}}
{{$partitionTable := or (Contains Stored.partition.Method.String "RANGE") (Contains Stored.partition.Method.String "LIST")}}
                <fieldset>
                     <legend><a href="javascript:;" onclick="$('#partition-setting').toggleClass('hidden')">{{"分区设置"|T}}</a></legend>
<div class="col-sm-12{{if le (len Stored.partition.Names) 1}} hidden{{end}}" id="partition-setting">
    <div class="col-sm-4">
                     <select name="partition_method" class="form-control" onchange="onselectPartition(this)">
                         <option value=""></option>
                         {{range $k,$v := Stored.partitionTypes}}
                         <option value="{{$v}}"{{if eq Stored.partition.Method.String $v}} selected="selected"{{end}}>{{$v}}</option>
                         {{end}}
                     </select>
    </div>
    <div class="col-sm-4">
        <div class="input-group">
<label class="input-group-addon">(</label>
<input name="partition_expression" class="form-control" title="{{"字段名或表达式"|T}}" value="{{Stored.partition.Expression.String}}">
<label class="input-group-addon">)</label>
        </div>
    </div>
    <div class="col-sm-4">
        <div class="input-group" id="partition_position"{{if or $partitionTable (not Stored.partition.Method.String)}} style="display:none"{{end}}>
<label class="input-group-addon">{{"分区"|T}}: </label>
<input type="number" name="partition_position" title="{{"数量"|T}}" class="form-control" value="{{Stored.partition.Position.String}}">
        </div>
    </div>
    <div class="col-sm-12">
<table cellspacing="0" id="partition-table"{{if not $partitionTable}} style="display:none"{{end}}>
<thead><tr><th>{{"分区名"|T}}</th><th style="width:50%">{{"值"|T}}</th><th style="width:70px">
        <a href="javascript:;" onclick="addPartitionRow()" class="label label-success" title="{{"下一行插入"|T}}"><i class="fa fa-plus"></i></a></th></tr></thead>
<tbody>
{{range $k,$v := Stored.partition.Names}}
	<tr>
    <td><input name="partition_names[]" class="form-control" value="{{$v}}" autocapitalize="off"></td>
	<td><input name="partition_values[]" class="form-control" value="{{index Stored.partition.Values $k}}"></td>
	<td>
        <a href="javascript:;" onclick="addPartitionRow(this)" class="label label-success" title="{{"下一行插入"|T}}"><i class="fa fa-plus"></i></a>
        <a href="javascript:;" onclick="delPartitionRow(this)" class="label label-danger" title="{{"移除"|T}}"><i class="fa fa-times"></i></a>
    </td>
    </tr>
{{end}}
</tbody>
</table>
    </div>
</div><!-- /.col-sm-12 -->
                </fieldset>
{{end}}

                </div>
              </div>

              
              <div class="form-group form-submit-group">
				<div class="col-sm-9 col-sm-offset-2">
				  <button type="submit" class="btn btn-primary btn-lg"><i class="fa fa-save"></i> {{"保存"|T}}</button>
				  <a class="btn btn-default btn-lg" href="{{dbMgrURL "privileges"}}" data-pjax="#pcont" data-keepjs="true"><i class="fa fa-reply"></i> {{"返回"|T}}</a>
				</div>
			</div>
              </form>
          </div><!-- /.content -->
        </div><!-- /.block-flat -->
    </div>
</div>
{{/Block}}
{{Block "footer"}}
{{Super}}
<script>
function addRow(obj) {
    var clone,currentTR,firstTR,hasNext,clone;
    if(obj==null){
        firstTR=$('#tbody-content > tr:first');
        hasNext=firstTR.next('tr').length>0;
        clone=firstTR.clone();
    }else{
        currentTR=$(obj).parent().parent();
        hasNext=currentTR.next('tr').length>0;
        clone=currentTR.clone();
    }
    var index=Number(clone.find('input[name="auto_increment"]').val());
    var oldIdx=index;
    index++;
    clone.find('[name^="fields["]').each(function(){
        var name=$(this).attr('name');
        switch(name){
            case 'fields['+oldIdx+'][field]':
            case 'fields['+oldIdx+'][orig]':
            case 'fields['+oldIdx+'][comment]':
            case 'fields['+oldIdx+'][default]':
            case 'fields['+oldIdx+'][length]':
            $(this).val('');
            break;
            case 'fields['+oldIdx+'][has_default]':
            case 'fields['+oldIdx+'][null]':
            $(this).prop('checked',false);
        }
        $(this).attr('name',name.replace(new RegExp('\\['+oldIdx+'\\]'),'['+index+']'));
    });
    clone.find('input[name="auto_increment"]').prop('checked',false).val(index);
    if(obj==null){
        firstTR.before(clone);
        reorder();
        return;
    }
    currentTR.after(clone);
    if(hasNext){
        clone=currentTR.next('tr');
        while(clone.next('tr').length>0){
            index++;
            clone=clone.next('tr');
            clone.find('input[name="auto_increment"]').val(index);
            clone.find('[name^="fields["]').each(function(){
                var name=$(this).attr('name');
                $(this).attr('name',name.replace(new RegExp('\\[[0-9]+\\]'),'['+index+']'));
            });
        }
    }
}
function delRow(obj) {
    if($('#tbody-content > tr').length<2){
        App.message({text:'{{"请至少保留一个字段，不能全部删除"|T}}',class_name:'warning',title:'{{"提醒"|T}}'},false);
        return;
    }
    $(obj).parent().parent().hide().find('input[name$="][field]"]').remove();
    reorder();
}
function reorder(){
    $('#tbody-content input[name="auto_increment"]').each(function(index,elem){
        $(this).val(index);
        
        $(this).parent().parent().parent().find('[name^="fields["]').each(function(){
            var name=$(this).attr('name');
            $(this).attr('name',name.replace(new RegExp('\\[[0-9]+\\]'),'['+index+']'));
        });
    });
}
function moveUpRow(obj) {
    var currentTR=$(obj).parent().parent();
    if(currentTR.prev('tr').length>0){
        currentTR.prev('tr').before(currentTR.clone());
        currentTR.remove();
        reorder();
    }
}
function moveDownRow(obj) {
    var currentTR=$(obj).parent().parent();
    if(currentTR.next('tr').length>0){
        currentTR.next('tr').after(currentTR.clone());
        currentTR.remove();
        reorder();
    }
}
function onselectType(obj) {
    var name=$(obj).attr('name');
    var prefix=name.substring(0,name.lastIndexOf("["));
    var tr=$(obj).parent().parent();
    switch($(obj).find('option:selected').parent('optgroup').data('type')){
        case 'String':
        case 'List':
            tr.find('select[name="'+prefix+'[collation]"]').show().siblings('select').hide();
            break;
        case 'ForeignKey':
            tr.find('select[name="'+prefix+'[on_delete]"]').show().siblings('select').hide();
            break;
        case 'Number':
            tr.find('select[name="'+prefix+'[unsigned]"]').show().siblings('select').hide();
            break;
        case 'Datetime':
            switch($(obj).val()){
                case 'datetime':
                case 'timestamp':
                tr.find('select[name="'+prefix+'[on_update]"]').show().siblings('select').hide();
                return;
            }
        default:
            tr.find('select[name="'+prefix+'[unsigned]"]').hide().siblings('select').hide();
    }
}
{{if Stored.supportPartitioning}}
function onselectPartition(obj){
    var v=$(obj).val();
    switch(v){
        case 'RANGE':
        case 'LIST':
        $('#partition-table').show();
        $('#partition_position').hide();
        break;
        case '':
        $('#partition-table').hide();
        $('#partition_position').hide();
        break;
        default:
        $('#partition-table').hide();
        $('#partition_position').show();
    }
}
function addPartitionRow(obj) {
    var clone,firstTR,currentTR;
    if(obj==null){
        firstTR=$('#partition-table > tbody > tr:first');
        clone=firstTR.clone();
    }else{
        currentTR=$(obj).parent().parent();
        clone=currentTR.clone();
    }
    clone.find('input[name="partition_names[]"]').val('');
    clone.find('input[name="partition_values[]"]').val('');
    if(obj==null){
        firstTR.before(clone);
        return;
    }
    currentTR.after(clone);
}
function delPartitionRow(obj) {
    if($('#partition-table > tbody > tr').length<2){
        App.message({text:'{{"请至少保留一行，不能全部删除"|T}}',class_name:'warning',title:'{{"提醒"|T}}'},false);
        return;
    }
    $(obj).parent().parent().remove();
}
{{end}}
$(function(){
    $.get(window.location.href,{json:'collations'},function(r){
        if(r.Code<1){
            return App.message(r.Info);
        }
        var str='',sel=$('#collation').attr('rel');
        for(var i in r.Data){
            str+='<optgroup label="'+i+'">';
            for(var j in r.Data[i]){
                var s=sel==r.Data[i][j].Collation.String?' selected="selected"':'';
                str+='<option value="'+r.Data[i][j].Collation.String+'"'+s+'>'+r.Data[i][j].Collation.String+'</option>';
            }
            str+='</optgroup>';
        }
        $('#collation').html(str);
        $('select.select-collation').each(function(){
            var sel=$(this).attr('rel');
            $(this).html('<option value="">({{"字符集"|T}})</option>'+str);
            if(sel){
                $(this).find('option[value="'+sel+'"]').prop('selected',true);
            }else{
                $(this).find('option:selected').prop('selected',false);
            }
        });
    },'json');
    {{if Stored.supportPartitioning}}
    onselectPartition('select[name="partition_method"]');
    {{end}}
});
</script>
{{/Block}}